package com.gy.hadoop.juc.thread;

import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 生产者消费者案例  使用queue完成
 */
public class ProdConsByQueue {

    private static volatile Boolean flag = true;

    public static void main(String[] args) {
        final BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);

        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                while (flag) {
                    String data = UUID.randomUUID().toString();
                    try {
                        boolean rt = queue.offer(data, 2L, TimeUnit.SECONDS);
                        if (rt) {
                            System.out.println(Thread.currentThread().getName() + "\t" + "插入队列" + data + "成功");
                        } else {
                            System.out.println(Thread.currentThread().getName() + "\t" + "插入队列" + data + "失败");
                        }
                        TimeUnit.SECONDS.sleep(1L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "prod_" + i).start();
        }


        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                while (flag) {
                    try {
                        String rt = queue.poll(2L, TimeUnit.SECONDS);
                        if (Objects.isNull(rt) || StringUtils.isEmpty(rt)) {
                            flag = !flag;
                            System.out.println(Thread.currentThread().getName() + "\t超过2秒钟没有消费，退出消费");
                            return;
                        }
                        System.out.println(Thread.currentThread().getName() + "\t消费队列" + rt + "成功");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "cons_" + i).start();
        }

    }


}


